# -*- coding: utf-8 -*-
import importlib
import os
import json
from util import db
import socket
import re
from multiprocessing import Process
from flask import Flask, session, redirect, url_for, escape,request,Response,render_template,make_response

app = Flask(__name__)

class MyRequest():
    def __init__(self,request,cursor_standard,mysql_52,cursor_33):
        self.request = request
        self.form = request.form
        self.cursor_standard = cursor_standard
        self.mysql_52 = mysql_52
        self.cursor_33 = cursor_33
        self.para = {}

        #封装分页参数
        if "page" in request.form and "rows" in request.form:
            page = request.form.get("page")
            rows = request.form.get("rows")
            start= (int(page) - 1)*int(rows)
            self.para['start'] = start
        print(self.form)

    #为防止sql注入，所有数据要全部去空格
    def formatSql(self,sql):
        for key in self.form:
            sp = "${"+key+"}"
            value = request.form.get(key).replace(" ",'')
            sql = sql.replace(sp,value)
        for key in self.para:
            sp = "${"+key+"}"
            value = str(self.para[key]).replace(" ","")
            sql = sql.replace(sp,value)
        print(sql)
        return sql

    def get(self,key):
        return self.form.get(key)

    def set(self,key,value):
        self.para[key] = value

@app.route('/', methods=["GET"])
def index():
    return render_template('system/system.html')

@app.route('/<dir>/<file>.html', methods=["GET"])
def html(dir,file):
    return render_template(dir+'/'+file+'.html',CDN="http://192.168.1.52:88")


@app.route('/<dir>/<file>/<method>', methods=['POST','GET'])
def api(dir,file,method):

    #标准库数据源
    conn_standard = db.get_mysql_52("standard")
    conn_standard.autocommit(True)
    cursor_standard = conn_standard.cursor()

    #中间库数据源
    conn_52 = db.get_mysql_52("middle")
    conn_52.autocommit(True)
    mysql_52 = conn_52.cursor()

    #测试库
    conn_33 = db.get_conn_theme_33()
    conn_33.autocommit(True)
    cursor_33 = conn_33.cursor()

    myRequest = MyRequest(request,cursor_standard,mysql_52,cursor_33)

    #根据请求路径获取对象python文件
    controller = importlib.import_module('controller.{}.{}'.format(dir,file))
    # 调用python文件中的相应方法，传入的参数是myRequest 实例
    result = eval('controller.{}(myRequest)'.format(method))
    cursor_standard.close()
    conn_standard.close()
    return  result


if __name__ == '__main__':
    app.run(host='0.0.0.0',port='33',debug=True)

